import 'package:flutter/material.dart';
import 'package:chewie/chewie.dart';
import 'package:video_player/video_player.dart';
import 'dart:async';
import '../utils/request.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class VideoSwiper extends StatefulWidget {
  var arguments;
  VideoSwiper({Key? key, this.arguments}) : super(key: key);

  @override
  _VideoSwiperState createState() => _VideoSwiperState(this.arguments);
}

class _VideoSwiperState extends State<VideoSwiper> {
  var arguments;
  _VideoSwiperState(this.arguments);
  late VideoPlayerController _videoPlayerController;
  late ChewieController _chewieController;
  late PageController _pageContronller;
  int currentIndex = 0;
  int videoIndex = 0;
  int _oldIndex = -1;
  var videoArr = [];
  bool _isChange = false;
  bool _canPlay = false;
  int _currentNum = 0;
  initVideo(url) async {
    _videoPlayerController = await VideoPlayerController.network(url);
    // _videoPlayerController.initialize();
    _chewieController = await ChewieController(
      videoPlayerController: _videoPlayerController,
      aspectRatio: 16 / 9,
      autoPlay: url == '' ? false : true,
      looping: false,
      showControls: true,
    );
    if (url != '') {
      this.setState(() {
        _oldIndex = currentIndex;
        _currentNum = currentIndex;
        _canPlay = true;
      });
    }
  }

  void _getVideoUrl(id) async {
    this.setState(() {
      _canPlay = false;
    });
    EasyLoading.show(status: 'loading...');
    var res = await getHttp('/mv/url?id=$id&r=960');
    EasyLoading.dismiss();
    var _url = res['data']['url'];
    var _newUrl = _url.replaceAll('http', 'https');
    initVideo(_newUrl);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    initVideo('');
    this.setState(() {
      videoIndex = arguments['currentIndex'];
      currentIndex = arguments['currentIndex'];
      _currentNum = arguments['currentIndex'];
      videoArr = arguments['ids'];
    });
    _pageContronller = PageController(initialPage: currentIndex);
    _getVideoUrl(videoArr[videoIndex]);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    initVideo('');
    _videoPlayerController.dispose();
    _chewieController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("视频播放"),
      ),
      body: Listener(
        onPointerDown: (event) {
          this.setState(() {
            _isChange = false;
          });
        },
        onPointerUp: (upPointEvent) {
          var _duration = Duration(milliseconds: 200);
          // 延迟200毫秒判断是因为，如果用户滑的很快，onPointerUp和onchange的执行顺序是不一样的
          // 所以200毫秒之后再做判断
          Timer(_duration, () {
            if (_isChange) {
              // 变了
              if (_oldIndex > currentIndex) {
                print("上滑");
              } else {
                print("下滑");
              }
              _getVideoUrl(videoArr[currentIndex]);
            } else {
              print("没有变化 ----");
            }
          });
        },
        child: PageView.builder(
          scrollDirection: Axis.vertical,
          itemCount: videoArr.length,
          controller: _pageContronller,
          onPageChanged: (index) {
            this.setState(() {
              this.currentIndex = index;
              _isChange = index == _oldIndex ? false : true;
            });
          },
          itemBuilder: (context, index) {
            return _currentNum == index
                ? Container(
                    color: Colors.black,
                    child: Center(
                      child: _canPlay
                          ? Chewie(controller: _chewieController)
                          : Icon(Icons.play_circle_filled, color: Colors.white),
                    ),
                  )
                : Center(
                    child: Container(
                      height: 200,
                      width: 600,
                      color: Colors.grey,
                      child: Center(
                        child: Icon(Icons.play_circle_filled, size: 80),
                      ),
                    ),
                  );
          },
        ),
      ),
    );
  }
}
// Chewie(controller: _chewieController)